<template lang="">
    <PageTitle>
        SHOLF:
        <template v-slot:buttons>
            <button class="btn btn-sm" 
                @click="$router.go(-1);">
                Назад
            </button>
        </template>
    </PageTitle>

    <ErrorAlert :message="error" v-if="error" />

    <form class="row row-cols-lg-auto g-3 align-items-center" id="sholfForm" @submit.prevent="send">

        <div class="input-group col-12">
            <label class="input-group-text" for="name">Алгоритм хэширования:</label>
            <select class="form-select" v-model="model.hashAlgorithm">
                <option value='0'>SHA256</option>
                <option value='1'>SHA512</option>
                <option value='2'>SHA1</option>
                <option value='3'>MD5</option>
            </select>
        </div>

        <div class="input-group col-12">
            <label class="input-group-text" for="name">Количество сегментов:</label>
            <input class="form-control" type="number" v-model="model.segmentCount" min="1" max="999" />
        </div>

        <div class="input-group col-12">
            <input class="form-control" type="file" id="fileSholf" @change="onUploadFile" name="fileSholf" />
        </div>

        <div class="col-12 mb-3">
            <button class="btn btn-sm btn-outline-success" type="submit" :disabled='loading'>
                <div v-if="loading">
                    <BSpinner small />
                    <span v-if="result.processingProgress == 0"> Загрузка файла на сервер...</span>
                    <span v-else> Обработка...</span>
                </div>
                <span v-else>Отправить</span>
            </button>
        </div>
    </form>

    <div v-if="loading && result.processingProgress > 0">
        <h5>Обработка...</h5>
        <BProgress :value="result.processingProgress" />
    </div>

    <ol class="list-group list-group-numbered list-group-flush" v-if="result.hash">
        <h5>Результат:</h5>
        <li class="list-group-item hash" v-for="str in result.hash">{{ str }}</li>
    </ol>
</template>
<script>
import * as signalR from '@microsoft/signalr';

export default {
    data() {
        return {
            connection: null,
            model: {
                hashAlgorithm: '0',
                segmentCount: 1,
                file: null
            },
            result: {
                hash: null,
                processingProgress: 0,
            },
            loading: false,
            error: null,
        }
    },
    methods: {
        onUploadFile(event) {
            this.model.file = event.target.files[0];
        },
        send: async function () {
            this.loading = true;
            this.result.hash = null;
            this.error = null;
            const url = "/api/ProjectExamples/SHOLF";

            let formData = new FormData();
            formData.append("hashAlgorithm", this.model.hashAlgorithm);
            formData.append("segmentCount", this.model.segmentCount);
            formData.append("connectionId", this.connection.connectionId);
            formData.append("file", this.model.file);
            
            const requestOptions = {
                method: 'POST',
                body: formData
            };
            const response = fetch(url, requestOptions);
            
            response.then(async response => {
                if (response.status === 200) {
                    this.result.hash = await response.json();
                    document.querySelector('#fileSholf').value = '';
                    this.result.processingProgress = 0;
                }
                else {
                    this.error = response.status + ": " + response.statusText;
                }
                this.loading = false;
            });
        },
        updateProcessingProgress(progress) {
            this.result.processingProgress = progress * 100;
        }
    },
    async created() {
        const hubConnection = new signalR.HubConnectionBuilder()
            .withUrl("/api/sholf")
            .build();

        hubConnection.on("UpdateLoadingBar", this.updateProcessingProgress);

        this.connection = hubConnection;
        this.connection.start();
    },
}
</script>
<style>
.hash {
  width: 100%;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
</style>